<?php
namespace app\service;

use GuzzleHttp\Client;
use Overtrue\Pinyin\Pinyin;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use think\facade\Config;

class CoupletService
{
    private $apiKey;
    private $baseUrl;

    public function __construct()
    {
        $config = Config::get('deepseek');
        $this->apiKey = $config['api_key'];
        $this->baseUrl = $config['base_url'];
    }

    public function identifyCouplet($sentence1, $sentence2)
    {
        // 先检查平仄规则
        $resultByTone = $this->checkByTone($sentence1, $sentence2);
        if ($resultByTone) return $resultByTone;

        // 平仄无法判断时调用AI模型
        return $this->checkByAI($sentence1, $sentence2);
    }

    private function checkByTone($s1, $s2)
    {
        $s1LastChar = mb_substr($s1, -1);
        $s2LastChar = mb_substr($s2, -1);

        $tone1 = $this->getTone($s1LastChar);
        $tone2 = $this->getTone($s2LastChar);

        if ($tone1 === '仄' && $tone2 === '平') {
            return ['上联' => $s1, '下联' => $s2];
        }

        if ($tone1 === '平' && $tone2 === '仄') {
            return ['上联' => $s2, '下联' => $s1];
        }

        return null;
    }

    private function getTone($char)
    {
        // 使用拼音库获取声调（示例实现）
        $pinyin = Pinyin::sentence($char);
        $tone = substr($pinyin, -1);

        // 判断平仄（简化为：一声二声为平，三声四声为仄）
        return in_array($tone, [1, 2]) ? '平' : '仄';
    }

    private function checkByAI($s1, $s2)
    {
        $client = new Client();

        $prompt = "请严格按json格式返回结果。判断以下哪个是上联，示例格式：{'上联' : '...', '下联' : '...'}\n对联A：$s1\n对联B：$s2";
        
        $response = $client->post($this->baseUrl, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'model' => 'deepseek-chat',
                'messages' => [
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => 0.3
            ]
        ]);

        $result = json_decode($response->getBody(), true);
        $cleanedString = str_replace('```', '', $result['choices'][0]['message']['content']);
        $str = str_replace('json','',$cleanedString);
        $aiResponse = json_decode($str, true);
        return [
            '上联' => $aiResponse['上联'],
            '下联' => $aiResponse['下联'],
        ];
    }
}